package servlet;

import DBC.DatabaseConnection;
import Factory.DAOFactory;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: hank
 * @create: 2021-03-28 21:37
 **/
@WebServlet("/getCourses")
public class getCoursesServlet extends HttpServlet {
    private final DatabaseConnection dbc = new DatabaseConnection();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Content-Type","text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String user = request.getParameter("user");
        Map<String,Object> map = new HashMap<>();
        try {
            map.put("CoursesList", DAOFactory.getDataInstance(this.dbc.getConn()).getCourse(user));
            map.put("EventsList", DAOFactory.getDataInstance(this.dbc.getConn()).getEvents(user));
            map.put("MeetingsList", "NULL");
            map.put("AllCoursesCount",DAOFactory.getDataInstance(this.dbc.getConn()).getCourse(user).size());
            map.put("Student_Name", DAOFactory.UserInfoInstance(this.dbc.getConn()).getUserInfo(user).get(0).getUser_Name());
            map.put("StateCode", 200);
        } catch (SQLException e) {
            e.printStackTrace();
        }catch (NumberFormatException e){
            map.put("StateCode", 500);
        }
        response.getWriter().print(com.alibaba.fastjson.JSONObject.toJSONString(map));
        System.out.println(user+"数据已获取");
        System.out.println("getCourses "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
